#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File : conv_playlist.py
@Time : 2024/02/08 13:25:23
@Author : ChenLJ 
@Version : 1.0
@Contact : morningcljin@outlook.com
@Desc : None
'''

# here put the import lib
import os
import json
import re

FILENAME = 'playlist.m3u8'
OUTPUT_FILENAME = 'playlist.json'

if __name__ == '__main__':
    
    if not os.path.exists(FILENAME):
        print (FILENAME, "not exist!")
    
    # 读取文件内容
    with open(FILENAME, "r", encoding='utf-8') as f:
        lines = f.read().splitlines()
        
    # 按行解析成dict
# {
#     "id": 0,
#     "videoIndex": 0,
#     "channel": "央视频道",
#     "logo": "https://resources.yangshipin.cn/assets/oms/image/202306/d57905b93540bd15f0c48230dbbbff7ee0d645ff539e38866e2d15c8b9f7dfcd.png?imageMogr2/format/webp",
#     "pid": "600001859",
#     "sid": "2000210103",
#     "programId": "600001859",
#     "needToken": false,
#     "mustToken": false,
#     "title": "CCTV1 综合",
#     "videoUrl": [
#       "http://dbiptv.sn.chinamobile.com/PLTV/88888890/224/3221226231/index.m3u8"
#     ]
#   },

# #EXTINF:-1 group-title="卫视台" tvg-id="重庆卫视" tvg-logo="https://live.fanmingming.com/tv/重庆卫视.png",重庆卫视
# http://221.213.43.82:8888/newlive/live/hls/31/live.m3u8
        jsonPlayList = []
        chId = 0
        for idx in range(len(lines)):
            channelDict = {"id": chId}
            line = lines[idx]
            if chId == 60:
                chId = chId
            if line[:7] == "#EXTINF":
                details = re.split(',| ', line)
                # details = line.split(',| ')
                for detail in details:
                    kv = detail.split("=")
                    if kv[0] == "group-title":
                        channelDict["channel"] = kv[1][1:-1]
                    elif kv[0] == "tvg-id":
                        channelDict["title"] = kv[1][1:-1]
                    elif kv[0] == "tvg-logo":
                        channelDict["logo"] = kv[1].split(",")[0][1:-1]
                        
                idx += 1
                channelDict["videoUrl"] = [lines[idx]]
                jsonPlayList.append(channelDict)
                chId += 1
                        
    # 保存为json文件
        json.dump(jsonPlayList, open(OUTPUT_FILENAME, "w", encoding='utf-8'), ensure_ascii=False, indent=4)
                  

    